﻿
using System.Security.Cryptography;

namespace Timo.Common.Extension;

/// <summary>
/// RSA加解密
/// </summary>
public static class RSAEncryptHelper
{
    private static string default_public_key { get; set; } = "a2023?01";  //公钥
    private static string default_private_key { get; set; } = "b2023?01"; //私钥

    /// <summary>
    /// 生成一对公钥和私钥：生成hash并转为键值对
    /// </summary>
    /// <returns></returns>
    public static KeyValuePair<string, string> GetKeyPair1()
    {
        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        string public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
        string private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
        return new KeyValuePair<string, string>(public_Key, private_Key);
    }
    /// <summary>
    /// 生成一对公钥和私钥：生成xml并转为键值对
    /// </summary>
    /// <returns></returns>
    public static KeyValuePair<string, string> GetKeyPair2()
    {
        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        string public_Key = RSA.ToXmlString(false);
        string private_Key = RSA.ToXmlString(true);
        return new KeyValuePair<string, string>(public_Key, private_Key);
    }

    /// <summary>
    /// RSA公钥加密
    /// </summary>
    /// <param name="str">待加密的字符串</param>
    /// <param name="public_key">公钥</param>
    /// <returns></returns>
    public static string RSAEncrypt(this string str, string? public_key = null)
    {
        var res = string.Empty;
        if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str))
            return res;        
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        if (string.IsNullOrEmpty(public_key) || string.IsNullOrWhiteSpace(public_key))
            public_key = default_public_key;
        byte[] cipherbytes;
        rsa.FromXmlString(public_key);
        cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(str), false);
        return Convert.ToBase64String(cipherbytes);
    }

    /// <summary>
    /// RSA解密
    /// </summary>
    /// <param name="str">密文</param>
    /// <param name="private_key">私钥</param>
    /// <returns></returns>
    public static string RSADecrypt(this string str, string? private_key = null)
    {
        var res = string.Empty;
        if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str))
            return res;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        if (string.IsNullOrEmpty(private_key) || string.IsNullOrWhiteSpace(private_key))
            private_key = default_private_key;
        byte[] cipherbytes;
        rsa.FromXmlString(private_key);
        cipherbytes = rsa.Decrypt(Convert.FromBase64String(str), false);

        return Encoding.UTF8.GetString(cipherbytes);
    }


}
